package com.example.order_engine.domain.service.impl;

import com.example.order_engine.domain.service.OrderValidator;
import com.example.order_engine.domain.model.Order;
import com.example.order_engine.domain.model.OrderItem;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 标准订单校验器实现
 */
@Component
public class StandardOrderValidator implements OrderValidator {
    
    @Override
    public boolean validate(Order order) {
        // 1. 基础校验
        if (order.getOrderId() == null || order.getOrderId().isEmpty()) {
            return false;
        }
        
        if (order.getCustomerId() == null || order.getCustomerId().isEmpty()) {
            return false;
        }
        
        // 2. 金额校验
        if (order.getTotalAmount() == null || order.getTotalAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return false;
        }
        
        // 3. 商品校验
        if (order.getItems() == null || order.getItems().isEmpty()) {
            return false;
        }
        
        for (OrderItem item : order.getItems()) {
            if (item.getPrice() == null || item.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
                return false;
            }
            if (item.getQuantity() == null || item.getQuantity() <= 0) {
                return false;
            }
        }
        
        // 4. 重新计算总金额校验
        BigDecimal calculatedTotal = order.getItems().stream()
            .map(OrderItem::getSubtotal)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        if (calculatedTotal.compareTo(order.getTotalAmount()) != 0) {
            return false;
        }
        
        return true;
    }
    
    @Override
    public String getSupportedOrderType() {
        return "STANDARD";
    }
}